<template>
  <el-select
    v-if="isEdit"
    class="base-timezone"
    :value="bindTimezone"
    :disabled="!isEdit"
    filterable
    :filter-method="filterMethod"
    @change="handleChange">
    <el-option
      v-for="v of showTimezoneList"
      :key="v.zoneId"
      :label="v.introduce"
      :value="v.zoneId"
    ></el-option>
  </el-select>

  <span v-else>
    {{ tzStr }}
  </span>
</template>
<script>
import { defineComponent, ref, unref, toRef, computed, watchEffect } from 'vue';
import { useTimezone, useTimezoneList } from 'pub-bbx-utils'

const { timezone } = useTimezone()

export default defineComponent({
  name: 'BaseTimezone',
  props: {
    // 选中的时区值
    value: {
      type: String,
      default: timezone,
    },
    // 是否编辑模式，编辑可切换时区
    isEdit: {
      type: Boolean,
      default: true,
    }
  },
  emits: ['change', 'input'],
  setup(props, { emit }) {
    // 获取时区列表
    const { timezoneList, currentTimezone, getTimezoneList, findZoneIdByTimezone, getTimezoneByZoneId } = useTimezoneList()

    function useBindTimezone(timezone) {
      // 真实时区值
      const bindTimezone = ref('')
      function setTimezone() {
        if (unref(timezone) !== unref(bindTimezone)) {
          bindTimezone.value = (unref(timezone) && findZoneIdByTimezone(unref(timezone))) || unref(currentTimezone)
        }
      }
      getTimezoneList().then(setTimezone)
      watchEffect(setTimezone)

      return {
        bindTimezone,
      }
    }

    // 绑定时区
    const { bindTimezone } = useBindTimezone(toRef(props, 'value'))

    // 时区回显
    const tzStr = !props.isEdit ? computed(() => getTimezoneByZoneId(unref(bindTimezone))) : ''

    // 切换时区
    function handleChange(value){
      emit('input', value)
      emit('change', value)
    }

    const filterKey = ref('')
    const showTimezoneList = computed(() => {
      return unref(filterKey) ? timezoneList.value.filter(v => {
        // 描述、时区id、子时区id 包含的候选列表
        return v.introduce.toLowerCase().includes(unref(filterKey))
          || v.zoneId.toLowerCase().includes(unref(filterKey))
          || v.subZoneIds?.some(id => id.toLowerCase().includes(unref(filterKey)))
      }) : timezoneList.value
    })

    function filterMethod(key){
      filterKey.value = key.toLowerCase()
      return []
    }

    return {
      bindTimezone,
      tzStr,
      timezoneList,
      showTimezoneList,
      handleChange,
      filterMethod,
    }
  }
});
</script>
<style lang="scss">
.base-timezone {
  flex: 1;
  width: 100%;
}
</style>